//
//  UIViewController+Route.m
//  WProjectForNative
//
//  Created by HuangZhen on 16/9/9.
//  Copyright © 2016年 HuangZhen. All rights reserved.
//

#import "UIViewController+Route.h"
#import <JLRoutes.h>
#import "NSString+URLEncoding.h"
@implementation UIViewController (Route)

+ (void)registerRoute:(NSString *)route withHandler:(BOOL(^)(NSDictionary *parameters))handler {
    [[JLRoutes globalRoutes]addRoute:route handler:^BOOL(NSDictionary<NSString *,id> * _Nonnull parameters) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
        NSMutableArray *strArray = [NSMutableArray arrayWithArray:[dic[@"JLRoutePattern"]componentsSeparatedByString:@"/"]];
        [strArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:[NSString class]] && [obj hasPrefix:@":"]) {
                NSString *key = [obj stringByReplacingOccurrencesOfString:@":" withString:@""];
                dic[key] = [dic[key] stringByURLDecoding];
            }
        }];
        return handler(dic);
    }];
}

- (void)triggerRoute:(NSString *)route withParameters:(NSDictionary *)parameters {
    NSURL *url = [NSURL URLWithString:route];
    NSMutableDictionary *parametersWithSelf = [NSMutableDictionary dictionaryWithDictionary:parameters];
    __weak typeof(self) weakSelf = self;
    parametersWithSelf[@"controller"] = weakSelf;
    [[JLRoutes globalRoutes] routeURL:url withParameters:parametersWithSelf];

}

@end
